//
//  SFPlayerRequestManager.m
//  Test
//
//  Created by xueshan1 on 2018/11/15.
//  Copyright © 2018年 xueshan1. All rights reserved.
//

#import "SFPlayerRequestManager.h"
#import "NSURL+stream.h"

@interface SFPlayerRequestManager ()<NSURLSessionDataDelegate>

@property(nonatomic,strong)NSURLSession *session;
@property(nonatomic,strong)NSURLSessionDataTask *task;

@end

@implementation SFPlayerRequestManager

- (instancetype)initWithRequestUrl:(NSString *)requestUrl
{
    self = [super init];
    if (self) {
        self.requestURL = requestUrl;
        [SFFileHandle createTempFileWithPathComponent:requestUrl.lastPathComponent];
    }
    return self;
}
- (void)setCancel:(BOOL)cancel{
    _cancel = cancel;
    [self.task cancel];
    [self.session invalidateAndCancel];
}
- (void)startRequest{
    NSURL *url = [[NSURL URLWithString:self.requestURL] originalSchemeURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0];
    //seek后,需要指定请求范围
    if (self.requestOffset > 0) {
        //Range: bytes=40-100 ：第40个字节到第100个字节之间的数据.
        [request addValue:[NSString stringWithFormat:@"bytes=%ld-%ld",self.requestOffset,self.fileLength-1] forHTTPHeaderField:@"Range"];
    }
    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    self.task = [self.session dataTaskWithRequest:request];
    [self.task resume];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    if (self.cancel) return;
//    NSLog(@"response:%@",response);
    completionHandler(NSURLSessionResponseAllow);
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSString *contentLength = [[httpResponse allHeaderFields]objectForKey:@"Content-Length"];
    self.fileLength = contentLength.integerValue>0 ? contentLength.integerValue : httpResponse.expectedContentLength;
    
    
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    if (self.cancel) return;
    
    [SFFileHandle writeTempFileData:data];
    self.cacheLength += data.length;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(sessionRequestDidReceiveData:)]) {
        [self.delegate sessionRequestDidReceiveData:data];
    }
    
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    if (self.cancel){
        NSLog(@"didComplete 下载取消");
    }else{
        if (error) {
            NSLog(@"下载出错:%@",error);
        }else{
            if (self.cache) {
                //将临时文件 copy 存储的缓存文件夹
                [SFFileHandle saveTempFileWithFileName:self.requestURL.lastPathComponent];
            }
            if (self.delegate && [self.delegate respondsToSelector:@selector(sessionRequestDidFinishLoadingWithCache:)]) {
                [self.delegate sessionRequestDidFinishLoadingWithCache:self.cache];
            }
            
            NSLog(@"load finish");
        }
        
    }
 
}

@end
